package com.rbac.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.common.utils.ThreadLocalUtil;
import com.domain.dto.login.LoginDto;
import com.domain.dto.login.MenuDTO;
import com.domain.dto.login.MenuTreeDTO;
import com.domain.vo.login.LoginVo;
import com.rbac.mapper.LoginMapper;
import com.rbac.mapper.UserMapper;
import com.rbac.pojo.Permission;
import com.rbac.pojo.User;
import com.rbac.service.ILoginService;
import org.mapstruct.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Mapper(componentModel = "spring")
interface msLoginMapper{
    MenuDTO PermissionToMenuDTO(Permission permission);
}

@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    msLoginMapper msLoginMapper;
    @Autowired
    LoginMapper loginMapper;
    @Autowired
    UserMapper userMapper;

    //构建角色菜单树
    @Override
    public List<MenuTreeDTO> getMenuTree(Integer userId) {
        //查询用户的角色
        List<Permission> permissions = loginMapper.getPermissionByUserId(userId);
        System.out.println(permissions);
        List<MenuTreeDTO> menuTreeDTOS = new ArrayList<>();
        for(Permission permission : permissions){

            MenuTreeDTO menuTreeDTO = new MenuTreeDTO();
            menuTreeDTO.setMenu(msLoginMapper.PermissionToMenuDTO(permission));
            menuTreeDTOS.add(menuTreeDTO);
        }

        List<MenuTreeDTO> parentList = menuTreeDTOS.stream()
                        .filter(item -> item.getMenu().getParentId() == 0)
                        .toList();
        buildMenuTree(parentList, menuTreeDTOS);

        return parentList;
    }

    @Override
    public LoginVo checkLogin(LoginDto loginDto) {
        String username = loginDto.getUsername();
        String password = loginDto.getPassword();

        User existUser = userMapper.selectOne(new QueryWrapper<User>().eq("username",username));
        if(existUser == null){
            throw new RuntimeException("查询为空");
        }else if(!existUser.getPassword().equals(password)){
            throw new RuntimeException("密码不匹配，请重新输入");
        }
//        System.out.println(existUser);
        int userId = existUser.getUserId();
        //通过redis 获取token，
        String token = "114514";
        LoginVo loginVo = new LoginVo();
        loginVo.setUserId(userId);
        loginVo.setToken(token);
        return loginVo;
    }

    @Override
    public User login(String username, String password) {
        User user = loginMapper.getUserByName(username);
        if(user == null){
            throw new RuntimeException("用户查找失败");
        }

        if(!user.getPassword().equals(password)){
            throw new RuntimeException("账号密码不匹配");
        }

        return user;
    }

    @Override
    public List<String> getPermsListByUserId(Integer userId) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer threadUserId = (Integer) claims.get("userId");
        if(!threadUserId.equals(userId)){
            throw new RuntimeException("账号id和查询id不匹配，查询失败");
        }
        return loginMapper.getPermsListByUserId(userId);
    }


    private void buildMenuTree(List<MenuTreeDTO> parentList, List<MenuTreeDTO> TreeDatas) {
        for(MenuTreeDTO parent : parentList) {
            List<MenuTreeDTO> childrenList = TreeDatas.stream()
                    .filter(menuTree -> Objects.equals(menuTree.getMenu().getParentId(), parent.getMenu().getPermissionId()))
                    .toList();
            parent.setChildrenList(childrenList);
            buildMenuTree(childrenList, TreeDatas);
        }
    }
}
